//
//  ScanPayFirstVC.m
//  LazyCat
//
//  Created by jike on 16/3/29.
//  Copyright (c) 2016年 zhanshu. All rights reserved.
//

#import "ScanPayFirstVC.h"
#import "ZBarScanVC.h"
#define ADD_DIGIT(x) [_resultText appendFormat:@"%d",x]
#define ADD_INPUT(x) [_inputText appendFormat:@"%d",x]
@interface ScanPayFirstVC ()<UITextFieldDelegate>

@end 

@implementation ScanPayFirstVC
{
    UITextField *_noteLabel;//备注
    //UILabel *_resultLabel;//结果
    UITextField *_resultLabel;//结果
    NSMutableString *_resultText;
    NSMutableString *_inputText;//输入后显示的字符串
    NSInteger *operation;
    BOOL _isResult;
    NSString *_endText;//最终结果
    NSMutableString *_inStr;//输入的字符。。。。。
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
}
-(void)initNav:(NSString*)title doBack:(BOOL)doBack {
    self.navBar.hidden=NO;
    //_resultText = [NSMutableString stringWithString:@"0"];
    _inputText = [NSMutableString stringWithFormat:@""];
    self.titleLable.text=title;
    self.titleLable.textColor = [UIColor whiteColor];
    if (doBack) {
        self.backBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        self.backBtn.frame=CGRectMake(8, 20+(44-21)/2, 12, 21);
        [self.backBtn setNormalImageWith:@"lALOCzPrgiYW_22_38"];
        [self.backBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.backBtn setHitTestEdgeInsets:UIEdgeInsetsMake(-10, -14, -14, -25)];
        [self.navBar addSubview:self.backBtn];
    }
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
-(void)backAction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)createUI {
    [self initNav:@"扫码收款" doBack:YES];
    self.navBar.backgroundColor = SetColor(0, 140, 206, 1);
    self.view.backgroundColor = [UIColor whiteColor];
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, 140)];
    backView.backgroundColor = SetColor(0, 140, 206, 1);
    [self.view addSubview:backView];
    
    UIControl *control=[[UIControl alloc]initWithFrame:self.view.frame];
    [control addTarget:self action:@selector(endEditHideKey) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:control];
    [self.view sendSubviewToBack:control];
    
    UIView *textBackView = [[UIView alloc]initWithFrame:CGRectMake(10, 10, ScreenWidth - 20, 120)];
    textBackView.backgroundColor = SetColor(77, 175, 221, 1);
    [backView addSubview:textBackView];
    
    _noteLabel = [[UITextField alloc]initWithFrame:CGRectMake(10, 0, textBackView.width - 20, 25)];
    _noteLabel.placeholder = @"点击添加备注,帮您记录交易目的";
    _noteLabel.font = [UIFont systemFontOfSize:13];
    _noteLabel.textColor = SetColor(219, 239, 248, 1);
    _noteLabel.delegate = self;
    _noteLabel.clearButtonMode=UITextFieldViewModeWhileEditing;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[NSForegroundColorAttributeName] = SetColor(219, 239, 248, 1);
    NSAttributedString *attribute = [[NSAttributedString alloc] initWithString:_noteLabel.placeholder attributes:dict];
    [_noteLabel setAttributedPlaceholder:attribute];
    [textBackView addSubview:_noteLabel];
    
    _resultLabel = [[UITextField alloc]initWithFrame:CGRectMake(10, 60, textBackView.width - 20, 60)];
    _resultLabel.textAlignment = NSTextAlignmentRight;
    _resultLabel.font = [UIFont systemFontOfSize:30];
    _resultLabel.text = @"0";
    _resultLabel.delegate = self;
    _resultLabel.adjustsFontSizeToFitWidth = YES;
    _resultLabel.textColor = [UIColor whiteColor];
    [textBackView addSubview:_resultLabel];
    
    
    
    _endText = @"0";
    int spaceW;
    int spaceH;
    spaceW = 375/ScreenWidth * 15;
    
    NSInteger width;
    width = (ScreenWidth - 5*spaceW)/4;
    spaceH = ((ScreenHeight - 264 - 10) - 4 * width)/5;
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
            if (i == 2 && j == 3) {
                btn.frame = CGRectMake(spaceW * (j+1) + j*width,204 + spaceH * (i+1) + i * width, width, width*2 + spaceW);
                btn.layer.cornerRadius = width/2;
                btn.clipsToBounds = YES;
                btn.layer.borderWidth = 0.5;
                btn.layer.borderColor = SetColor(225, 225, 225, 1).CGColor;
            }else if (i ==3 && j == 3){
                
            }else {
                btn.frame = CGRectMake(spaceW * (j+1) + j*width,204 + spaceH * (i+1) + i * width, width, width);
                btn.layer.cornerRadius = width/2;
                btn.clipsToBounds = YES;
                btn.layer.borderWidth = 1;
                btn.layer.borderColor = SetColor(225, 225, 225, 1).CGColor;
            }
            if (i == 3) {
                if (j == 0) {
                    [btn setTitle:@"0" forState:UIControlStateNormal];
                }else if (j == 1){
                    [btn setTitle:@"." forState:UIControlStateNormal];
                }else if(j ==2) {
                    [btn setTitle:@"+" forState:UIControlStateNormal];
                }
            }else {
                if (i == 0 && j == 3) {
                    [btn setTitle:@"删除" forState:UIControlStateNormal];
                    [btn setBackgroundImage:[UIImage imageNamed:@"backBtnPic"] forState:UIControlStateNormal];
                }else if (i == 1 && j == 3){
                    [btn setTitle:@"清空" forState:UIControlStateNormal];
                    [btn setBackgroundImage:[UIImage imageNamed:@"backBtnPic"] forState:UIControlStateNormal];
                }else if (i == 2 && j == 3){
                    [btn setTitle:@"=" forState:UIControlStateNormal];
                }else{
                    [btn setTitle:[NSString stringWithFormat:@"%d",i*3 + j + 1] forState:UIControlStateNormal];
                }
            }
            btn.tag = i * 4 + j+1;
            [btn setTitleColor:SetColor(80, 80, 80, 1) forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
            btn.enabled = YES;
            [btn setBackgroundImage:[UIImage imageNamed:@"backBtnPic"] forState:UIControlStateHighlighted];
            btn.backgroundColor = [UIColor whiteColor];
            [self.view addSubview:btn];
        }
    }
    
    //底部view
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight - 74, ScreenWidth, 74)];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];
    NSArray *titleArr = @[@"支付宝收款",@"微信收款"];
    for (int i = 0; i< 2; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        NSInteger width = (ScreenWidth - 15 * 3)/2;
        btn.frame = CGRectMake(15 + 15*i + width*i, 15, width, 44);
        if (i == 0) {
            btn.backgroundColor = SetColor(0, 140, 206, 1);
        }else if (i == 1){
            btn.backgroundColor = SetColor(81, 190, 50, 1);
        }
        btn.layer.cornerRadius = 44/2;
        btn.clipsToBounds = YES;
        btn.tag = 111+i;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitle:titleArr[i] forState:UIControlStateNormal];
        [bottomView addSubview:btn];
    }
    _isResult = NO;
}
-(void)endEditHideKey
{
    [_noteLabel resignFirstResponder];
}
//
- (void)buttonPressed:(UIButton *)sender
{
    if (deleteInput) {
        [_resultText setString:@""];
    }
    if ([_inputText isEqualToString:@"0"]) {
        _inputText = [NSMutableString stringWithString:@""];
    }
    deleteInput = NO;
    NSArray *arr = [_inputText componentsSeparatedByString:@"+"];
    NSArray *pointArr = [_inputText componentsSeparatedByString:@"."];
    BOOL isPoint;
    isPoint = [[arr lastObject] length] < 9;
    
    switch (sender.tag) {
        case 8://清空
            // reset screen
            _endText = @"0";
            _inputText = [NSMutableString stringWithString:@""];
            leftOperator = nil;
            break;
        case 1:
            if (isPoint) {
                ADD_INPUT(1);
            }
            break;
        case 2:
            if (isPoint) {
                ADD_INPUT(2);
            }
            break;
        case 3:
            if (isPoint) {
                ADD_INPUT(3);
            }
            break;
        case 4:
            if (_inputText.length >= 1) {
                [_inputText deleteCharactersInRange:NSMakeRange(_inputText.length - 1, 1)];
            }
            break;
        case 5:
            if (isPoint) {
               ADD_INPUT(4);
            }
            
            break;
        case 6:
            
            if (isPoint) {
                ADD_INPUT(5);
            }
            break;
        case 7:
            if (isPoint) {
                ADD_INPUT(6);
            }
            break;
        case 15://加
            if ([[arr lastObject]length] == 0) {
            }else {
                [_inputText appendString:@"+"];
            }
            break;
        case 9:
            if (isPoint) {
                ADD_INPUT(7);
            }
            break;
        case 10:
            if (isPoint) {
                ADD_INPUT(8);
            }
            break;
        case 11:
            if (isPoint) {
                ADD_INPUT(9);
            }
            break;
        case 13://0
            if (isPoint) {
                ADD_INPUT(0);
            }
            break;
        case 12://=
            [self doOperation:0];
            //deleteInput = YES;
            _isResult = YES;
            break;
    }
    
    // prettify result
    //NSLog(@"%@",_resultText);
    //_resultText = [self readableNumberFromString:_resultText];
   _inputText = [self readableNumberFromString:_inputText];
    
    // check if we need to add a dot, like Apple's calculator does.
    if ([sender tag] == 14) {
        NSArray *arr = [_inputText componentsSeparatedByString:@"+"];
        if ([[arr lastObject] rangeOfString:@"."].location != NSNotFound) {
        }else {
            [_inputText appendString:@"."];
        }
    }
    // finally show the text to the user
    if (_isResult) {
        _resultLabel.text = _endText;
        _isResult = NO;
    }else {
        _resultLabel.text = _inputText;
    }
}

- (BOOL)isTwoCharLeftThePoint:(NSString *)str {
    
    
    return YES;
}

- (BOOL)shouldStrBeInput:(NSString *)str Type:(NSString *)type{
    NSArray *arr = [str componentsSeparatedByString:@"+"];
    BOOL diandian;
    if ([type isEqualToString:@"dian"]) {
        diandian =[[arr lastObject] rangeOfString:@"+"].location != NSNotFound;
    }else if ([type isEqualToString:@"jia"]){
        diandian =[[arr lastObject]rangeOfString:@"+"].location != NSNotFound;
    }
    return diandian;
}
- (NSMutableString *)readableNumberFromString:(NSString *)aString
{
    // given 12.30000 we remove the trailing zeros
    NSMutableString *result = [NSMutableString stringWithString:aString];
    
    // check if it contains a . character.
    if ([result rangeOfString:@"."].location != NSNotFound) {
        // start from the end, and remove any 0 or . you find until you find a number greater than 0
        for (int i = [result length] - 1; i >= 0; i--) {
            // get the char
            unichar currentChar = [result characterAtIndex:i];
//            if (currentChar == '0') {
//                // remove it from the string
//                //[result replaceCharactersInRange:NSMakeRange(i, 1) withString:@""];
//            } else
                if (currentChar == '.') {
                // remove it from the string
                    if (i == [result length] - 1) {
                        
                    }
                //[result replaceCharactersInRange:NSMakeRange(i, 1) withString:@""];
                break;
            }else {
                break;
            }
            
        }
    }
    // assign default value if needed
    if ([result isEqualToString:@""]) {
        [result appendString:@"0"];
    }
    
    // remove the initial 0 if present
//    if ([result length] > 1 && [result characterAtIndex:0] == '0') {
//        [result replaceCharactersInRange:NSMakeRange(0, 1) withString:@""];
//    }
    
    
    return result;
}
//clear number's zero
- (NSString *)changeFloat:(NSString *)Right {
    NSString *stringFloat;
    stringFloat = Right;
    //[NSString stringWithFormat:@"%.10f",Right];
    const char *floatChars = [stringFloat UTF8String];
    NSUInteger length = [stringFloat length];
    NSUInteger zeroLength = 0;
    int i;
    for(i = length-1; i>=0; i--)
    {
        if(floatChars[i] == '0') {
            zeroLength++;
        }
        else {
            if(floatChars[i] == '.') {
                i--;
            }
            break;
        }
    }
    NSString *returnString;
    returnString = (i==-1) ? @"0" : [stringFloat substringToIndex:i+1];
    return returnString;	
}
- (void)doOperation:(int)theOperation
{
    if (theOperation == 0)
        theOperation = operation;
    double result;
    NSString *str = (NSString *)_inputText;
    NSLog(@"--%@",str);
    double a = 0;
    NSArray *moneyArr = [str componentsSeparatedByString:@"+"];
    for (int i = 0; i < moneyArr.count; i++) {
        a += [moneyArr[i] doubleValue];
        _endText = (NSMutableString *)[NSString stringWithFormat:@"%.2f",a];
    }
    //去掉小数点后多余的0
//    NSString * testNumber = _endText;
//    NSString * s = nil;
//    int offset = testNumber.length - 1;
//    if ([testNumber rangeOfString:@"."].location != NSNotFound) {
//        while (offset)
//        {
//            s = [testNumber substringWithRange:NSMakeRange(offset, 1)];
//            if ([s isEqualToString:@"0"] || [s isEqualToString:@"."])
//            {
//                offset--;
//            }
//            else
//            {
//                break;
//            }
//        }
//    }
//    
//    NSString * outNumber = [testNumber substringToIndex:offset+1];
    //NSLog(@"%@", outNumber);
        result = [leftOperator doubleValue] + [_resultText doubleValue];
    
    // reset the leftOperator
    leftOperator = nil;
}
- (void)performOperation:(int)theOperation
{
    // if we have a right operator already, compute the existing value
    if (leftOperator) {
        [self doOperation:theOperation];
    } else {
        // save the existing operation for later
        //operation = theOperation;
    }
    // assign the left operation for later use
    leftOperator = [NSNumber numberWithDouble:[_resultText doubleValue]];
}
#pragma mark -- 跳转到扫码支付
- (void)btnClick:(UIButton *)sender {
    [self doOperation:0];
    //_isResult = YES;
    if (sender.tag == 111) {//支付宝
        ZBarScanVC *scanVC = [[ZBarScanVC alloc]init];
        scanVC.moneyStr = _endText;
        scanVC.PayType = @"1";
        scanVC.notesStr = _noteLabel.text;
        if ([_endText isEqualToString:@"0"] || [_endText isEqualToString:@"0.00"]) {
            [[MessShowView share] showWithMess:@"金额不能为0"];
        }else {
           [self.navigationController pushViewController:scanVC animated:YES];
        }
    }else if (sender.tag == 112){//微信
        ZBarScanVC *scanVC = [[ZBarScanVC alloc]init];
        scanVC.moneyStr = _endText;
        scanVC.PayType = @"2";
        scanVC.notesStr = _noteLabel.text;//备注
        if ([_endText isEqualToString:@"0"] || [_endText isEqualToString:@"0.00"]) {
            [[MessShowView share] showWithMess:@"金额不能为0"];
        }else {
            [self.navigationController pushViewController:scanVC animated:YES];
        }
    }
}
#pragma _noteLabel代理方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_noteLabel resignFirstResponder];
    return YES;
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField == _resultLabel) {
        return NO;
    }else {
        return YES;
    }
}
//- (NSString *)judeg

//- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
//{
//    //if (textField == _priceField) {
//    NSScanner      *scanner    = [NSScanner scannerWithString:string];
//    NSCharacterSet *numbers;
//    NSRange         pointRange = [textField.text rangeOfString:@"."];
//    
//    if ( (pointRange.length > 0) && (pointRange.location < range.location  || pointRange.location > range.location + range.length) )
//    {
//        numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
//    }
//    else
//    {
//        numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
//    }
//    
//    if ( [textField.text isEqualToString:@""] && [string isEqualToString:@"."] )
//    {
//        return NO;
//    }
//    
//    short remain = 2; //默认保留2位小数
//    
//    NSString *tempStr = [textField.text stringByAppendingString:string];
//    NSUInteger strlen = [tempStr length];
//    if(pointRange.length > 0 && pointRange.location > 0){ //判断输入框内是否含有“.”。
//        if([string isEqualToString:@"."]){ //当输入框内已经含有“.”时，如果再输入“.”则被视为无效。
//            return NO;
//        }
//        if(strlen > 0 && (strlen - pointRange.location) > remain+1){ //当输入框内已经含有“.”，当字符串长度减去小数点前面的字符串长度大于需要要保留的小数点位数，则视当次输入无效。
//            return NO;
//        }
//    }
//    
//    NSRange zeroRange = [textField.text rangeOfString:@"0"];
//    if(zeroRange.length == 1 && zeroRange.location == 0){ //判断输入框第一个字符是否为“0”
//        if(![string isEqualToString:@"0"] && ![string isEqualToString:@"."] && [textField.text length] == 1){ //当输入框只有一个字符并且字符为“0”时，再输入不为“0”或者“.”的字符时，则将此输入替换输入框的这唯一字符。
//            textField.text = string;
//            return NO;
//        }else{
//            if(pointRange.length == 0 && pointRange.location > 0){ //当输入框第一个字符为“0”时，并且没有“.”字符时，如果当此输入的字符为“0”，则视当此输入无效。
//                if([string isEqualToString:@"0"]){
//                    return NO;
//                }
//            }
//        }
//    }
//    
//    NSString *buffer;
//    if ( ![scanner scanCharactersFromSet:numbers intoString:&buffer] && ([string length] != 0) )
//    {
//        return NO;
//    }
//    
//    //}
//    
//    return YES;
//}

@end
